<template>
    <div class="app-container">
        <div style="margin-bottom: 20px">
            <el-input
                v-model="listQuery.id"
                placeholder="ID"
                style="width: 160px;"
                class="filter-item"
                @input="handleFilter"
            />
            <el-input
                v-model="listQuery.title"
                placeholder="文章标题"
                style="width: 200px;margin-left: 10px"
                class="filter-item"
                @input="handleFilter"
            />
            <el-cascader
                v-model="listQuery.catIdList"
                placeholder="所属大类"
                style="margin-left: 10px"
                :options="options"
                :props="props"
                :show-all-levels="false"
                collapse-tags
                clearable
                @change="handleFilter"
            />
            <el-select
                v-model="listQuery.status"
                placeholder="大类状态"
                style="width: 160px;margin-left: 10px"
                multiple
                @change="handleFilter"
            >
                <el-option label="显示" :value="1" />
                <el-option label="隐藏" :value="0" />
            </el-select>
        </div>

        <el-table
            v-loading="listLoading"
            :data="list"
            border
            fit
            highlight-current-row
            style="width: 100%"
        >
            <el-table-column
                align="center"
                label="ID"
                width="100"
                prop="id"
                sortable
            />

            <el-table-column align="center" label="Order" width="120" prop="listOrder" sortable>
                <template slot-scope="{row}">
                    <el-input-number
                        v-model="row.listOrder"
                        controls-position="right"
                        :min="0"
                        size="small"
                        style="width: 90px"
                        @change="handleOrderUpdate(row.id, row.listOrder)"
                    />
                </template>
            </el-table-column>

            <el-table-column min-width="260px" label="标题">
                <template slot-scope="{row}">
                    <router-link :to="'/post/edit/'+row.id" class="link-type">
                        <span>{{ row.title }}</span>
                    </router-link>
                </template>
            </el-table-column>

            <el-table-column
                width="100px"
                align="center"
                label="阅读量"
                prop="count"
                sortable
            />

            <el-table-column
                width="100px"
                align="center"
                label="类别名称"
                prop="catId"
            >
                <template slot-scope="{row}">
                    <router-link :to="{ path: '/post/list', query: { cid: row.catId }}">
                        <span class="link-type">{{ row.catName }}</span>
                    </router-link>
                </template>
            </el-table-column>

            <el-table-column
                width="100px"
                align="center"
                label="来源"
                prop="authorName"
            />

            <el-table-column class-name="status-col" label="状态" width="110">
                <template slot-scope="{row}">
                    <el-tag :type="row.newsStatus | statusTypeFilter">
                        {{ row.newsStatus | statusNameFilter }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column align="center" label="操作" width="300">
                <template slot-scope="scope">
                    <router-link :to="'/post/edit/'+scope.row.id">
                        <el-button type="primary" size="small" icon="el-icon-edit">
                            编辑
                        </el-button>
                    </router-link>
                    <el-button type="info" size="small" style="margin-left: 10px" icon="el-icon-setting" plain @click="handleStatusChange(scope)">
                        切换状态
                    </el-button>
                    <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteRow(scope.$index)" />
                </template>
            </el-table-column>

            <el-table-column
                width="160px"
                align="Order"
                label="创建时间"
                prop="createTime"
                sortable
            />

            <el-table-column
                width="160px"
                align="Order"
                label="更新时间"
                prop="updateTime"
                sortable
            />
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { changePostOrder, deletePost, getPostList, switchPostStatus } from '@/api/post'
import { getCategoryTree } from '@/api/category'
import { convertListToParam } from '@/utils/axios-formatter' // Secondary package based on el-pagination

export default {
    name: 'ArticleList',
    components: { Pagination },
    filters: {
        statusTypeFilter(status) {
            const statusMap = ['info', 'success']
            return statusMap[status]
        },
        statusNameFilter(status) {
            const statusMap = ['隐藏', '显示']
            return statusMap[status]
        }
    },
    data() {
        return {
            list: null,
            total: 0,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 20,
                id: undefined,
                title: '',
                catIdList: [],
                status: []
            },
            options: [],
            props: { // 级联选择框规则
                value: 'id',
                label: 'name',
                multiple: true
            }
        }
    },
    computed: {
        catId() {
            return Number(this.$route.query && this.$route.query.cid)
        }
    },
    watch: {
        catId: function(val) {
            this.selectCatId(val)
        }
    },
    created() {
        // 再判断是不是通过大类跳转过来, 选择初始化方式
        if (this.catId) {
            getCategoryTree({ include: 'home' }).then(data => {
                this.options = data
                this.selectCatId(this.catId)
            })
        } else {
            getCategoryTree({ include: 'home' }).then(data => {
                this.options = data
            })
            this.getList()
        }
    },
    methods: {
        // 直接请求数据
        getList() {
            this.listLoading = true
            const params = Object.assign({}, this.listQuery)

            // TODO: 暂时修复catId为空的问题, 大类选择没法加入缓存, 用路径表示可解决
            if (this.listQuery.catIdList && this.listQuery.catIdList[0]) {
                params.catIdList = convertListToParam(this.listQuery.catIdList.map(item => item[item.length - 1]))
            } else {
                params.catIdList = ''
            }

            params.status = convertListToParam(params.status)
            getPostList(params).then(data => {
                this.list = data.content
                this.total = data.totalSize
                this.listLoading = false
            }).catch(err => {
                console.log(err)
            })
        },
        // 根据当前筛选条件请求数据
        handleFilter() {
            this.getList()
            this.listQuery.page = 1
        },
        // 添加大类ID筛选条件
        selectCatId(catId) {
            // 获取完整路径
            const findIndexArray = (arr, indexArray = []) => {
                const newArr = Array.from(indexArray) // 浅拷贝
                for (let i = 0; i < arr.length; ++i) {
                    const item = arr[i]
                    newArr.push(item.id)
                    if (item.id === catId) {
                        return newArr
                    }
                    if (item.children && item.children.length > 0) {
                        const result = findIndexArray(item.children, newArr)
                        if (result) return result
                    }
                    newArr.pop()
                }
                return false
            }
            const rtnArr = findIndexArray(this.options)
            this.listQuery.catIdList = [rtnArr]
            this.handleFilter()
        },
        handleOrderUpdate(id, order) {
            changePostOrder(id, order)
                .then(() => {
                    this.$message.success('order更新成功')
                })
        },
        handleStatusChange(scope) {
            const _id = scope.row.id
            switchPostStatus(_id).then(() => {
                scope.row.newsStatus = scope.row.newsStatus === 0 ? 1 : 0
                this.$message({
                    type: 'success',
                    message: '状态修改成功'
                })
            })
        },
        deleteRow(index) {
            this.$confirm('此操作将永久删除当前文章, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const _id = this.list[index].id
                deletePost(_id).then(() => {
                    this.list.splice(index, 1)
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    })
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        }
    }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
